package com.moarea.app.service.abst;

import com.moarea.app.http.impl.OkHttpFactory;
import com.moarea.app.http.inter.OkHttpCaller;
import com.moarea.app.lang.model.ResultObject;
import com.moarea.app.service.impl.BaseService;
import com.moarea.app.service.inter.IHTTPService;
import net.sf.json.JSONObject;

import java.io.IOException;

/**
 * HTTP服务接口实现
 * <p>
 * jizhong
 * <p>
 * 2017-09-22
 */
public abstract class AHTTPService extends BaseService implements IHTTPService {

    /**
     * 发起POST/GET请求
     * <p>
     * 如果是POST,请求参数为JSON格式字符串
     * <p>
     * content-type=application/json;utf-8
     *
     * @param url    请求连接
     * @param json   参数
     * @param method POST/GET
     * @return 结果[ResultObject]对象
     */
    @Override
    public ResultObject callHttpAccess(String url, String json, String method) {

        boolean callPortFaild = false;
        String result;
        //使用net.sf.json作为解析工具
        JSONObject jsonObject = null;

        try {

            OkHttpCaller caller = OkHttpFactory.newOkHttpCaller();
            result = "GET".equals(method.toUpperCase()) ?
                    caller.callGetSync(url) : caller.callPostSync(url, json);

            jsonObject = JSONObject.fromObject(result);
        } catch (IOException e) {
            callPortFaild = true;
        }

        if (callPortFaild) {
            //调用失败，这里的情形是网络不通、接口报错等原因导致返回的是空串，转换成Json的时候就会报错
            return ResultObject.createInstance(false, "网络连接或服务器内部错误！");
        } else {

            ResultObject resultObject = ResultObject.createInstance();
            resultObject.setSuccess(true);
            resultObject.setMessage("接口调用成功");
            resultObject.setData(jsonObject);

            return resultObject;
        }
    }
}
